package com.huonan.jb.tools.fileuse.compare;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huonan.utils.DateUtils;
import com.huonan.utils.FileUtils2;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class StaticsHandler {
    private static final int BATCH_SIZE = 5000;
    public static final String STATISTICS_FIELD = "kw_id";
    public static final boolean HAS_FILE = true;

    /**
     * 统计逻辑
     * 发布时间按天统计
     * hasFile:是否需求统计文件
     */
    private synchronized static void statics(JSONObject obj, File file) {
        Cache cache = Cache.getInstance();
        String staticField = obj.getStr(STATISTICS_FIELD);
        //如果是日期，需要格式化
        String formatDate = DateUtils.formatDate(staticField);
        try {
            cache.putMapValueAdd(STATISTICS_FIELD, staticField);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 统计原始文件是否包含某条数据
     */
    private synchronized static void staticMatchData(JSONObject obj, File file) {
        Cache cache = Cache.getInstance();
        List<String> compareContent = CompareFiles.getCompareContent();
        String staticField = obj.getStr(STATISTICS_FIELD);
        if (compareContent.contains(staticField)) {
            try {
                cache.putMapValueContact(STATISTICS_FIELD, staticField, file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static CompletableFuture<String> staticByFile(ExecutorService executorService,
                                                         File file) {
        CompletableFuture<String> future = null;
        try {
            future = CompletableFuture.supplyAsync(() -> {
                int totalCount = 0;
                try (FileUtils2 reader = new FileUtils2(file.getAbsolutePath(), BATCH_SIZE)) {
                    while (true) {
                        List<String> lines = reader.readNextLines();
                        for (String line : lines) {
                            JSONObject obj = JSONUtil.parseObj(line);
                            staticMatchData(obj, file);
                        }
                        if (lines.size() == 0) {
                            break;
                        }
                        totalCount += lines.size();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("file line count:{}", totalCount);
                return "";
            }, executorService);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return future;
    }

    // 打印统计信息
    public static void printStaticInfo() {
        Cache cache = Cache.getInstance();
        Set<Map.Entry<String, String>> cacheAll = cache.getMapAll(StaticsHandler.STATISTICS_FIELD);
        AtomicInteger total = new AtomicInteger();
        log.info("result");
        cacheAll.forEach(e -> {
            if (!HAS_FILE) {
                total.addAndGet(Integer.parseInt(e.getValue()));
            }
            log.info("{}-{}", e.getKey(), e.getValue());
        });
        log.info("total-{}", total);
        cache.clear();
    }
}
